# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import os
import sys

import svn.core

import gvn.changebranch
import gvn.cmdline
import gvn.errors


helptext__gvn_approve = """approve: Approve a changebranch.
usage: approve CHANGE
"""


def TryApprove(change_name, ctx, pool):
  try:
    (username, name, revision) = gvn.util.ParseChangeName(change_name)
    cb = gvn.changebranch.ChangeBranch(ctx.config, ctx.project,
                                       name, username, revision)
    cb.Approve(pool)
  except gvn.errors.User, e:
    ctx.Notify('%s\n' % (e,))
    return e.code

  ctx.Notify("approved '%s'\n" % (cb.change_name,), pool)
  return 0


def Handle_GvnApprove(ctx):
  ctx.wc_operands = False
  iterpool = svn.core.Pool(ctx.pool)
  rval = 0
  for change_name in ctx.operands:
    iterpool.clear()
    r = TryApprove(change_name, ctx, iterpool)
    if r != 0:
      # Use the last error code as the exit code.
      rval = r
  iterpool.destroy()

  return rval


gvn.cmdline.AddCommand('approve', Handle_GvnApprove, helptext__gvn_approve,
                       gvn.cmdline.AuthOptions(['project', 'quiet']))
